<?php

class Material extends BaseMaterial
{
	
public function __toString()
  {
  	
  	
    return $this->getTitle();
  
  }
	

  public function getTitle()
  {
  	 
  	  	return $this->title;
  	 
  }
  
public function setContent($v)
  {
   $v = str_replace('&nbsp;',' ',$v);
   parent::setContent($v);
  }
  
public function getContent()
  {
   return str_replace('&nbsp;',' ',$this->content);
  }  
  
  public function delete(PropelPDO $con = null)
  {
  	 if($this->getTypeId()==2)
  	 {
  	 	if($this->getParentId()>0)
  	 	{
  	 		$mat = MaterialPeer::retrieveByPK($this->getParentId());
  	 		$mat->setTitle(trim($mat->getTitle()));
  	 		$mat->setSee(0);
  	 		$mat->save();
  	 	}
  	 }

  	 ///Удаляем картинки
  	 if($this->getPhotoPath()!='')
  	 {
  	 	$fname = sfConfig::get('sf_upload_dir').'/material/'.$this->getTypeMaterial()->getImageFolder().'/'.$this->getPhotoPath();
	  	$fname2 = sfConfig::get('sf_upload_dir').'/material/'.$this->getTypeMaterial()->getImageFolder().'/'.$this->getPhotoPath().'.flv';
	    $fthname = sfConfig::get('sf_upload_dir').'/material/thumbnail/'.$this->getTypeMaterial()->getImageFolder().'/'.$this->getPhotoPath();
	    $_fthname = sfConfig::get('sf_upload_dir').'/material/_thumbnail/'.$this->getTypeMaterial()->getImageFolder().'/'.$this->getPhotoPath();
	
	    @unlink($fname);
	    @unlink($fname2);
	    @unlink($fthname);
	    @unlink($_fthname);
  	 }
  	 
  	 parent::delete();
  }
  
  public function save(PropelPDO $con = null)
  {
  	parent::save();
  	$folders = $this->getMat2Folders();
  	 $arr = array();
  	foreach($folders as $f)
  	{
  		  FolderPeer::recount ( $f->getFolder() );		
  		  $arr[$f->getFolder()->getLevel()] = $f->getFolder()->getId();		
  	}
  	 asort($arr);
  	 $str = implode(":", $arr);
  	 
  	$this->setNavigationFolder($str);
  	
  	//Устанавливаем все каталоки строкой
    $this->resetFoldersArray();

  	//parent::save();
  	
  	
  	if($this->type_id!=9 and $this->type_id!=10 and $this->type_id!=11 and $this->type_id!=12)
  	{
     // $this->generateThumbnail ( $this->getPhotoPath() );
	  //$this->generateThumbnailsmall ( $this->getPhotoPath() );
  	}
  	
  	///Устанавливаем флаги фото видео и файлов у родителя
  	if($this->parent_id>0 and ($this->type_id==5 or $this->type_id==9 or $this->type_id==12 or $this->type_id==6 or $this->type_id==18))
  	{
  		$pm = MaterialPeer::retrieveByPK($this->parent_id);
	  	$pm->setIsPhoto($pm->isPhotos());
	  	$pm->setIsFile($pm->isFiles());
	  	$pm->setIsVideo($pm->isVideos());
	  	$pm->setIsNews($pm->isNews());
	  	$pm->save();
  	}
  	
  	//// убиваем кеш
  	$dir = sfConfig::get('sf_app_cache_dir').'/template';
  	//echo $dir;
  	//die;
  	sfToolkit::clearDirectory($dir);
  	//////
  }
  
	
	public function resetFoldersArray()
	{
	  	//Устанавливаем все каталоки строкой
       $c = new Criteria();
       $c->add(Mat2FolderPeer::MATERIAL_ID,$this->id);
       $folders = Mat2FolderPeer::doSelect($c);
		  	$str = '';
		  	foreach($folders as $f)
		  	{
		  		 $str.=' '.$f->getFolder()->getId();		
		  	}
		  	$this->setFoldersArray($str);
		  	parent::save();
	}
  
  
  public function mysave(PropelPDO $con = null)
  {
  	parent::save();
  
  	
  }
  
public function getPhotoGallery()
  {
      $c = new Criteria();
      $c->add(MaterialPeer::TYPE_ID,5);
        if(!sfContext::getInstance()->getUser()->hasCredential('admin'))
      {
         $c->add(MaterialPeer::PUB,true);
      }
      $c->add(MaterialPeer::PARENT_ID,$this->id);  
      $c->addAscendingOrderByColumn(MaterialPeer::ID);
      $mats = MaterialPeer::doSelect($c);
      if($mats)
      {
      	 return $mats;
      }
      else 
      {
      	 return false;
      }
       
  }
  
public function getFiles()
  {
      $c = new Criteria();
      $c->add(MaterialPeer::TYPE_ID,9);
        if(!sfContext::getInstance()->getUser()->hasCredential('admin'))
      {
         $c->add(MaterialPeer::PUB,true);
      }
      $c->add(MaterialPeer::PARENT_ID,$this->id);
      $c->addAscendingOrderByColumn(MaterialPeer::ID);
      $mats = MaterialPeer::doSelect($c);
      if($mats)
      {
      	 return $mats;
      }
      else 
      {
      	 return false;
      }
     
      
  }
  
  
public function getVideoGallery()
  {
      $c = new Criteria();
      $c->add(MaterialPeer::TYPE_ID,12);
      if(!sfContext::getInstance()->getUser()->hasCredential('admin'))
      {
         $c->add(MaterialPeer::PUB,true);
      }
      $c->add(MaterialPeer::PARENT_ID,$this->id);
      $c->addAscendingOrderByColumn(MaterialPeer::ID);
      $mats = MaterialPeer::doSelect($c);
      if($mats)
      {
      	 return $mats;
      }
      else 
      {
      	 return false;
      }    
  }
  
  
public function getCompanyNews()
  {
      $c = new Criteria();
      $c->add(MaterialPeer::TYPE_ID,6);
        if(!sfContext::getInstance()->getUser()->hasCredential('admin'))
      {
         $c->add(MaterialPeer::PUB,true);
      }
      $c->add(MaterialPeer::PARENT_ID,$this->id);
      $c->addAscendingOrderByColumn(MaterialPeer::ID);
      $mats = MaterialPeer::doSelect($c);
      if($mats)
      {
      	 return $mats;
      }
      else 
      {
      	 return false;
      }    
  }
  
  
public function getCompanyFiles()
  {
      $c = new Criteria();
      $c->add(MaterialPeer::TYPE_ID,18);
      $c->add(MaterialPeer::PARENT_ID,$this->id);
      $c->addAscendingOrderByColumn(MaterialPeer::ID);
        if(!sfContext::getInstance()->getUser()->hasCredential('admin'))
      {
         $c->add(MaterialPeer::PUB,true);
      }
      $mats = MaterialPeer::doSelect($c);
      if($mats)
      {
      	 return $mats;
      }
      else 
      {
      	 return false;
      }    
  }
  
  
public function getPhotoCompany()
  {
      $c = new Criteria();
      $c->add(MaterialPeer::TYPE_ID,5);
      $c->add(MaterialPeer::PARENT_ID,$this->id);
      $mats = MaterialPeer::doSelect($c);
      if($mats)
      {
      	 return $mats;
      }
      else 
      {
      	 return false;
      }
     
      
  }
  
  
  
  public function getFolders()
  {
  	  $c = new Criteria();
  	  $c->addJoin(MaterialPeer::ID, Mat2FolderPeer::MATERIAL_ID);
  	  $c->addJoin(Mat2FolderPeer::FOLDER_ID,FolderPeer::ID);
  	  $c->add(FolderPeer::TREE_LEFT,1,Criteria::NOT_EQUAL);
  	  $c->add(MaterialPeer::ID,$this->id);
  	  $flds = FolderPeer::doSelect($c);
  	  if($flds)
  	  {
  	  	 return $flds;
  	  }
  	  else
  	  {
  	  	return  false;
  	  }
  	  
  }
  
    public function getPaket()
  {
    switch ($this->custom_int3) {
    case 1:
        return 'Тестовая регистрация';
        break;
    case 2:
       return 'Бизнес';
        break;
    case 3:
        return 'Премиум';
        break;
    case 4:
        return 'V.I.P';
        break;        
       }
  }
  
  
  
	public function setPhotoPath($value) {
		parent::setPhotoPath ( $value );

	}

	public function generateThumbnail($value) 
	{	
	  $uploadDir = sfConfig::get ( 'sf_upload_dir' ).'/material/'.$this->getTypeMaterial()->getImageFolder();
		if($value!='' and file_exists($uploadDir . '/' . $this->getPhotoPath ()))
		{	
		
		$thumbnail = new sfThumbnail ( $this->getTypeMaterial()->getImageWidth(), $this->getTypeMaterial()->getImageHeight() );
		$thumbnail->loadFile ( $uploadDir . '/' . $this->getPhotoPath () );
		$thumbnail->save ( $uploadDir . '/thumbnail/' . $this->getPhotoPath () );
		}
	}
  
	public function generateThumbnailsmall($value) 
	{		
	  $uploadDir = sfConfig::get ( 'sf_upload_dir' ).'/material/'.$this->getTypeMaterial()->getImageFolder();
		if($value!='' and file_exists($uploadDir . '/' . $this->getPhotoPath ()) )
		{
		
		$thumbnail = new sfThumbnail ( $this->getTypeMaterial()->getSimageWidth(), $this->getTypeMaterial()->getSimageHeight() );
		$thumbnail->loadFile ( $uploadDir . '/' . $this->getPhotoPath () );
		$thumbnail->save ( $uploadDir . '/_thumbnail/' . $this->getPhotoPath () );
		}
	}
  
	/*
	 * Получение ссылки на компанию из галереи
	 */
	public function getLinkToCompanySmall($folder_id)
  {		
		if($this->parent_id>0)
		{
			$str = link_to(image_tag('/uploads/material/gallery/_thumbnail/'.$this->getPhotoPath(),'title="'.$this.'"'),'@tab_2?id='.$this->parent_id,'style="height: auto"'); 
		}
		else 
		{
			$str = link_to(image_tag('/uploads/material/gallery/_thumbnail/'.$this->getPhotoPath(),'title="'.$this.'"'),'@gallery_list?folder_id='.$folder_id,'style="height: auto"'); 
		}
		
     return $str;
  }
  
  
  
  
public function getLinkToCompanyBig()
  {
  	
		
		if($this->parent_id>0)
		{
			$str = link_to(image_tag('/uploads/material/gallery/thumbnail/'.$this->getPhotoPath(),'title="'.$this.'"'),'@tab_2?id='.$this->parent_id); 
		}
		else 
		{
			$str = link_to(image_tag('/uploads/material/gallery/thumbnail/'.$this->getPhotoPath(),'title="'.$this.'"'),'@gallery_show?id='.$this->getId()); 
		}
		
     return $str;
  }
  
  
  
	/*
	 * Получение ссылки на компанию в виде логотипа статуса 
	 */
	public function getLinkLogoStatusOrg()
  {		
			  switch ($this->custom_int3) {
			    case 1:
			        $str = ''; 
			        break;
			    case 2:
			        $str = link_to(image_tag('/images/icons/icon_business.gif','title="'.__('Тестовая регистрация').'" width="35" class="floatleft" style="margin: 10px 0 0 0 "'),'@company_show?popup=false&id='.$this->id);
			        break;
			    case 3:
			        $str = link_to(image_tag('/images/icons/icon_premium.gif','title="'.__('Тестовая регистрация').'" width="35" class="floatleft" style="margin: 10px 0 0 0 "'),'@company_show?popup=false&id='.$this->id);
			        break;
			    case 4:
			        $str = link_to(image_tag('/images/icons/icon_vip.gif','title="'.__('Тестовая регистрация').'" width="35" class="floatleft" style="margin: 10px 0 0 0 "'),'@company_show?popup=false&id='.$this->id);
			    break;		
			    default:
			    	 
			     $str = '';
			    	break;	        
			}
		
		
     return $str;
  }
  
	public function getLogoStatusOrg()
  {		
			  switch ($this->custom_int3) {
			    case 1:
			       $str = image_tag('/images/icon_test.gif','title="'.__('Test регистрация').'" class="floatleft" style="margin: 10px 10px 0 0 "');
			        break;
			    case 2:
			        $str = image_tag('/images/icon_business.gif','title="'.__('Business регистрация').'" class="floatleft" style="margin: 10px 10px 0 0 "');
			        break;
			    case 3:
			        $str = image_tag('/images/icon_premium.gif','title="'.__('Premium регистрация').'" class="floatleft" style="margin: 10px 10px 0 0 "');
			        break;
			    case 4:
			        $str = image_tag('/images/icon_vip.gif','title="'.__('V.I.P. регистрация').'" class="floatleft" style="margin: 10px 10px 0 0 "');
			    break;		
			    default:
			    	 
			     $str = '';
			    	break;	        
			}
		
		
     return $str;
  }
  
  
  
public function getTypestr()
  {
	  switch ($this->getTypeId()) {
	    case 1:
	         return 'Предприятие';
	         break;
	    case 2:
	        return 'Персональная страница';
	         break;
	    case 3:
	        return 'Страница';
	    break;
	    case 4:
	        return 'Интернет ресурс';
	    break;
	    case 5:
	        return 'Изображение';
	    break;
	    case 6:
	        return 'Статья';
	    break;      
	    case 7:
	        return 'Журнал';
	     break;     
	    case 8:
	        return 'Объявление';        
	    break;
	    case 9:
	        return 'Файл';        
	    break; 
	    case 10:
	        return 'Новость';        
	    break; 
	    case 11:
	        return 'Подарок';        
	    break; 	   
	    case 12:
	        return 'Видеофайл';        
	    break; 
	    case 13:
	        return 'Семинар';        
	    break; 
	    case 14:
	        return 'Выставка';        
	    break; 	 
	    case 15:
	        return 'Новость';        
	    break; 		 
	    case 16:
	        return 'Ссылка';        
	    break; 	
	    case 18:
	        return 'Публикация-файл';        
	    break; 		    		          	     
	    default:
	    	return 'Тип не определен';     
	    	break; 
    }
  }
  
	
  //// Операции с тегами
  
  public function setTag($v)
  {
  	  parent::setTag($v);
  	  
  	  if(sfConfig::get('app_use_tag')==true and $this->id>0)
  	  {
  	  	 
  	  	 $arr = split(',',$v);
  	  	 foreach($arr as $a)
  	  	 {
  	  	 	$c = new Criteria();
  	  	 	$c->add(TagPeer::NAME,trim($a)); 
  	  	 	$cnt = TagPeer::doCount($c);
  	  	 	if($cnt==0)
  	  	 	{
	  	  	 	$tag = new Tag();
	  	  	 	$tag->setName(trim($a));
	  	  	 	$tag->save();
  	  	 	}
  	  	 }
  	  	 
  	     foreach($arr as $a)
  	  	 {
  	  	 	$c = new Criteria();
  	  	 	$c->add(Mat2tagPeer::TAG,trim($a)); 
  	  	 	$c->addAnd(Mat2tagPeer::MAT_ID,$this->id); 
  	  	 	$cnt = TagPeer::doCount($c);
  	  	 	if($cnt==0)
  	  	 	{
  	  	 	   $c = new Criteria();
  	  	 	   $c->add(TagPeer::NAME,trim($a));
  	  	 	   $t = TagPeer::doSelectOne($c);
  	  	 	   if($t)
  	  	 	   {
	  	  	   $m2t = new Mat2tag();
	  	  	   $m2t->setMatId($this->id);
	  	  	   $m2t->setTag(trim($a));
	  	  	   $m2t->setTagId($t->getId());
	  	  	   $m2t->save();
  	  	 	   }
  	  	 	}

  	  	 }
  	  	 
  	  }
  	 
  }
  
  
    public function getFilials()
  {
  	 $c = new Criteria();
  	 $c->add(MaterialPeer::PARENT_ID,$this->id);
  	 $c->add(MaterialPeer::TYPE_ID,1);
  	 $c->add(MaterialPeer::PUB,true);
  	 $m = MaterialPeer::doSelect($c);
  	 return $m;
  }
  
  
    public function isPhotos()
  {
  	 $c = new Criteria();
  	 $c->add(MaterialPeer::PARENT_ID,$this->id);
  	 $c->add(MaterialPeer::TYPE_ID,5);
  	 $c->add(MaterialPeer::PUB,true);
  	 $cnt = MaterialPeer::doCount($c);
  	 if($cnt>0)
  	 {
  	 	return true;
  	 }
  	 else 
  	 {
  	 	return false;
  	 }
  	 
  }
  
    public function isVideos()
  {
  	 $c = new Criteria();
  	 $c->add(MaterialPeer::PARENT_ID,$this->id);
  	 $c->add(MaterialPeer::TYPE_ID,12);
  	 $c->add(MaterialPeer::PUB,true);
  	 $cnt = MaterialPeer::doCount($c);
  	 if($cnt>0)
  	 {
  	 	return true;
  	 }
  	 else 
  	 {
  	 	return false;
  	 }
  	 
  }
  
    public function isFiles()
  {
  	 $c = new Criteria();
  	 $c->add(MaterialPeer::PARENT_ID,$this->id);
  	 $c->add(MaterialPeer::TYPE_ID,9);
  	 $c->add(MaterialPeer::PUB,true);
  	 $cnt = MaterialPeer::doCount($c);
  	 if($cnt>0)
  	 {
  	 	return true;
  	 }
  	 else 
  	 {
  	 	return false;
  	 }
  	 
  }
  
    public function isNews()
  {
  	 $c = new Criteria();
  	 $c->add(MaterialPeer::PARENT_ID,$this->id);
  	 $c->add(MaterialPeer::TYPE_ID,18);
  	 $c->add(MaterialPeer::PUB,true);
  	 $cnt = MaterialPeer::doCount($c);
  	 if($cnt>0)
  	 {
  	 	return true;
  	 }
  	 else 
  	 {
  	 	return false;
  	 }
  	 
  }
  
    public function getFirstPhone()
  {
  	 $arr = explode(',',$this->phone);
  	 if(is_array($arr))
  	 {
  	 	return $arr[0];
  	 }
  	 else
  	 {
  	 	return '';
  	 }
  }
  
   public function getRegionLine()
  {
       	  $c = new Criteria();
       	  $c->add(FolderPeer::TREE_LEFT,1,Criteria::NOT_EQUAL);
		  $c->add(Mat2FolderPeer::MATERIAL_ID,$this->id);
		  $c->addJoin(Mat2FolderPeer::FOLDER_ID,FolderPeer::ID);
		  $c->add(FolderPeer::SCOPE,sfConfig::get('app_scope_region'));
		  $c->addAscendingOrderByColumn(FolderPeer::TREE_LEFT);
		  $cf = FolderPeer::doSelect($c);	
		  if(!$cf)
		  {
       	  $c = new Criteria();
       	  $c->add(FolderPeer::TREE_LEFT,1,Criteria::NOT_EQUAL);
		  $c->add(Mat2FolderPeer::MATERIAL_ID,$this->id);
		  $c->addJoin(Mat2FolderPeer::FOLDER_ID,FolderPeer::ID);
		  $c->add(FolderPeer::SCOPE,19);
		  $c->addAscendingOrderByColumn(FolderPeer::TREE_LEFT);
		  $cf = FolderPeer::doSelect($c);		  	
		  }
		  $arr = array();
		  foreach($cf as $f)
		  {
		  	 $arr[]= $f;
		  }
		  return implode(',&nbsp;',$arr).', '.$this->city;
  }
		  
			

  public function getLinkDownload()
  {
  	$str = link_to($this->title,'http://'.$_SERVER['SERVER_NAME'].'/uploads/material/download/'.$this->id.'/'.$this->custom_file3);
  	return $str;
  }
	
  /*
   * Функции отчета по поиску 
   */
  
  public function getReportSearchKey()
  {
  	$c = new Criteria();
  	$c->add(Mat2FolderPeer::MATERIAL_ID,$this->id);
  	$keys = Mat2FolderPeer::doSelect($c);
  	$arr = '';
  	foreach ($keys as $k)
  	{
  		$arr.=' '.$k->getTag();
  	}
  	return str_replace('##',' ', $arr);
  }
  
  public function getReportSearchName()
  {
  	$c = new Criteria();
  	$c->add(SearchlogPeer::MAT_ID,$this->id);
  	$c->add(SearchlogPeer::LEVEL,3);
  	$cnt = SearchlogPeer::doCount($c);
  	return $cnt;
  }
  
  public function getReportSearchTag()
  {
  	$c = new Criteria();
  	$c->add(SearchlogPeer::MAT_ID,$this->id);
  	$c->add(SearchlogPeer::LEVEL,2);
  	$cnt = SearchlogPeer::doCount($c);
  	return $cnt;
  }
  
  
  public function getSearchActionsList($date_from, $date_to)
  {
  	$c = new Criteria();
  	$c->add(SearchlogPeer::MAT_ID,$this->id);
  	$c->add(SearchlogPeer::LEVEL,5);
  	$c->add(SearchlogPeer::CREATED_AT,$date_from,Criteria::GREATER_EQUAL);
  	$c->add(SearchlogPeer::CREATED_AT,$date_to,Criteria::LESS_EQUAL);
  	$c->addGroupByColumn(SearchlogPeer::KEY);
    $c->clearSelectColumns();
	$c->addSelectColumn('COUNT(' . SearchlogPeer::ID.')'); 
	$c->addSelectColumn(SearchlogPeer::KEY); 
    $stmt = PaymentPeer::doSelectStmt($c);
  	return $stmt;
  }
  
  public function getSearchActionsShow($date_from, $date_to)
  {
  	$c = new Criteria();
  	$c->add(SearchlogPeer::MAT_ID,$this->id);
  	$c->add(SearchlogPeer::LEVEL,6);
  	$c->add(SearchlogPeer::CREATED_AT,$date_from,Criteria::GREATER_EQUAL);
  	$c->add(SearchlogPeer::CREATED_AT,$date_to,Criteria::LESS_EQUAL);
  	$c->addGroupByColumn(SearchlogPeer::KEY);
    $c->clearSelectColumns();
	$c->addSelectColumn('COUNT(' . SearchlogPeer::ID.')'); 
	$c->addSelectColumn(SearchlogPeer::KEY); 
    $stmt = PaymentPeer::doSelectStmt($c);
  	return $stmt;
  }
  
}
